<?php

use mysql_xdevapi\BaseResult;
use Common\ORG\WxFunction;
use Common\ORG\PublicFunction;

function check_is_chu($jobs_id)
{
    //查询企业简历下载记录
    $companyDown    = M('CompanyDownResume')->where(['company_uid'=>C('visitor.uid')])->getField('resume_uid', true);

    $gwTuiJian  = M('GuwenTuiJianRusume')->where(['resume_uid'=>['in', $companyDown],'jobs_id'=> $jobs_id, 'comp_uid'=>C('visitor.uid'), ' tui_status'=>['in', [0,1]]])->find();
    if(!empty($gwTuiJian)) {
      return 0;
    }else{
       return 1;
    }
}




/**
 * 获取顾问的擅长职位和工程类别
 * @param $uid
 * @param $trade_list
 * @return mixed
 */
function get_guwen_good_trade_job($uid,$trade_list)
{
    $jian_info = M('resume')->field('fullname,intention_jobs,major_cn,good_jobs,good_trade')->where(['uid' => $uid])->find();
    $arr=explode(',',$jian_info['good_jobs']);
    $ids=[];
    foreach ($arr as $k1=>$v1){
        $cate_jobs=explode('.',$v1);
        if(!empty($cate_jobs[1])){
            $ids[]=$cate_jobs[1];
        }else{
            $ids[]=$cate_jobs[0];
        }
    }
    $tra_arr=explode(',',$jian_info['good_trade']);
    $tra_names=[];
    foreach ($tra_arr as $k1=>$v1){
        $cate_jobs=explode('.',$v1);
        if(!empty($cate_jobs[1])){
            $tra_names[]=  $trade_list[$cate_jobs[1]]['categoryname'] ;//$cate_jobs[1];
        }else{
            $tra_names[]=$trade_list[$cate_jobs[0]]['categoryname'];//$cate_jobs[0];
        }
    }
    $data['major_cn']=implode(',',$tra_names);
    $names=M('category_jobs')->where(['id'=>['in',$ids]])->getField('categoryname',true);
    $data['intention_jobs']=implode(',',$names);
    return $data;
}


function get_user_edu($uid)
{
    $res=M('resume_education')->where(['uid'=>$uid])->order('education desc')->find();
    return $res['education_cn']?$res['education_cn']:'暂无';
}


/**
 * /**
 * 添加企业购买 其邀请顾问获得分佣
 * @param $comp_uid
 * @param $order_type
 * @param $order_id
 * @return bool
 */
 function add_guwen_tui_com_give_money_log($comp_uid,$order_type,$order_id)
{
    //查询企业用户是不是我推荐的
    //是  判断订单类型  buy_taocan  购买套餐   buy_gcb 购买工程币  fa_bu 微信支付发布职位
//           $comp_uid=11;
//           $order_type='buy_taocan';
//           $order_id=29;
    $order_info=M('order')->where(['id'=>$order_id])->find();
    //var_dump($order_info);die;
    if(empty($order_info)){
        return true;
    }
    $com_info=M('company_profile')->where(['uid'=>$comp_uid])->find();
    //var_dump($com_info);
    if(empty($com_info)){
      //  die;
        return true;
    }
    $desc="企业【".$com_info['companyname']."】";
    switch ($order_type){
        case 'buy_taocan':
            $desc.="购买套餐";
            break;
        case 'buy_gcb':
            $desc.='购买工程币';
            break;
        case 'fa_bu':
            $desc.='发布职位';
    }
    $tui_info=M('guwen_user')->where(['uid'=>$comp_uid])->find();

    //var_dump($tui_info);
    if($tui_info){
        $money=($order_info['pay_amount']-$order_info['service_money'])*0.05;
      //  var_dump($money);die;
        add_guwen_money($tui_info['guwen_id'],$money,$desc,$order_type,1,0,0,0,0,$order_info['id'],$desc,$comp_uid,$money,2);

    //  die;
        return true;
    }
    return true;

}



/**
 * 验证是否可以推送简历
 * @param $jobs_id  职位ID
 * @param $comp_uid 企业用户ID
 * @param $order_id 发布订单ID
 * @param $uid 录用用户ID
 * @return int
 */

function check_is_can_tui($jobs_id,$comp_uid,$order_id,$uid=0)
{
    //判断是否显示可以去投建简历
    //查询职位的招聘人数
    $jobs_info=M('jobs')->where(['id'=>$jobs_id])->find();
    //判断已经录用的人数
    $jie_order_ids=M('gu_wen_jie_dan_order')->where(['jobs_id'=>$jobs_id,'fa_bu_order'=>$order_id,'comp_uid'=>$comp_uid])->getField('id',true);
    $where=[
        'jobs_id'=>$jobs_id,
        'order_id'=>['in',$jie_order_ids],
        'comp_uid'=>$comp_uid,
        'tui_status'=>['in',[1,3,4]],
    ];
    if($uid){
        $where['resume_uid']=['not in',[$uid]];
    }
   // var_dump(M('gu_wen_jie_dan_order')->getLastSql());die;
    if($jie_order_ids){
        $count=M('guwen_tui_jian_rusume')->where($where)->count();
        $count=$count?$count:0;
        if($count<$jobs_info['amount']){
            return 1;
        }
        return 0;
    }
    return 1;
}



/**
 * 添加购买套餐记录
 * @param $uid
 * @param $set_meal_id
 * @param int $type
 * @param int $last_num
 */
function add_gcb_log($uid,$set_meal_id,$type=2,$last_num=0)
{
   $res= M('buy_log')->add([
        'uid'=> $uid,
        'set_meal_id'=>$set_meal_id,
        'type'=>2,
        'add_time'=>date('Y-m-d H:i:s',time()),
        'last_num'=>$last_num,
    ]);

    return $res;
}


/**
 * 投递简历发送邮件
 */

function  send_email_by_jobsapplay($jobs_id,$rid)
{
//    $jobs_id=21;
//    $rid=1;
    $jobs_info=M('jobs')->where(['id'=>$jobs_id])->find();
    $resume =M('resume')->where(array('id' => $rid))->find();
    $body='申请贵司【'.$jobs_info['jobs_name'].'】职位-'.$resume['fullname'];
    $user_info=M('members')->where(['uid'=>$resume['uid']])->find();
    if($jobs_info['js_email']){
        $email=$jobs_info['js_email'];
        send_email($email,$rid,$body,$body,$user_info['email']);
        $com_info=M('company_profile')->where(['id'=>$jobs_info['company_id']])->find();
        $email2=$com_info['email'];
        send_email($email2,$rid,$body,$body,$user_info['email']);
    }else{
        $com_info=M('company_profile')->where(['id'=>$jobs_info['company_id']])->find();
        $email=$com_info['email'];
        send_email($email,$rid,$body,$body,$user_info['email']);
    }
}

/**
 * 发送简历
 * @param $email
 * @param $rid
 * @param $body
 * @param $note
 */

 function send_email($email,$rid,$body,$note,$fa_email)
{
    $res = D('Resume')->save_as_doc_word($rid, '', C('visitor'), 1,1);

   // var_dump($res);die;
    $site_url = M('config')->where(['name' => 'site_domain'])->find();
    $url = $site_url['value'] . $res['path'] . $res['name'];
  //  $email='773037977@qq.com';

    $result = sendMail($email, $body, $res['html'], $res['path'] . $res['name'], $res['name'],$res['fujian_one'],$res['fujian_two'],$fa_email);
 // var_dump($result);die;
}





/*
*function：计算两个日期相隔多少年，多少月，多少天
*param string $date1[格式如：2011-11-5]
*param string $date2[格式如：2012-12-01]
*return array array('年','月','日');
*/
function diffDate($date1,$date2){
    if(strtotime($date1)>strtotime($date2)){
        $tmp=$date2;
        $date2=$date1;
        $date1=$tmp;
    }
    list($Y1,$m1,$d1)=explode('-',$date1);
    list($Y2,$m2,$d2)=explode('-',$date2);
    $Y=$Y2-$Y1;
    $m=$m2-$m1;
    $d=$d2-$d1;
    if($d<0){
        $d+=(int)date('t',strtotime("-1 month $date2"));
        $m--;
    }
    if($m<0){
        $m+=12;
        $y--;
    }
    return array('year'=>$Y,'month'=>$m,'day'=>$d);
}



/**
 * Passport 加密函数
 *
 * @param        string          等待加密的原字串
 * @param        string          私有密匙(用于解密和加密)
 *
 * @return       string          原字串经过私有密匙加密后的结果
 */
function encrypt($txt, $key = '_qscms') {
    // 使用随机数发生器产生 0~32000 的值并 MD5()
    srand((double)microtime() * 1000000);
    $encrypt_key = md5(rand(0, 32000));
    // 变量初始化
    $ctr = 0;
    $tmp = '';
    // for 循环，$i 为从 0 开始，到小于 $txt 字串长度的整数
    for ($i = 0; $i < strlen($txt); $i++) {
        // 如果 $ctr = $encrypt_key 的长度，则 $ctr 清零
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        // $tmp 字串在末尾增加两位，其第一位内容为 $encrypt_key 的第 $ctr 位，
        // 第二位内容为 $txt 的第 $i 位与 $encrypt_key 的 $ctr 位取异或。然后 $ctr = $ctr + 1
        $tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
    }
    // 返回结果，结果为 passport_key() 函数返回值的 base64 编码结果
    return base64_encode(passport_key($tmp, $key));
}

/**
 * Passport 解密函数
 *
 * @param        string          加密后的字串
 * @param        string          私有密匙(用于解密和加密)
 *
 * @return       string          字串经过私有密匙解密后的结果
 */
function decrypt($txt, $key = '_qscms') {
    // $txt 的结果为加密后的字串经过 base64 解码，然后与私有密匙一起，
    // 经过 passport_key() 函数处理后的返回值
    $txt = passport_key(base64_decode($txt), $key);
    // 变量初始化
    $tmp = '';
    // for 循环，$i 为从 0 开始，到小于 $txt 字串长度的整数
    for ($i = 0; $i < strlen($txt); $i++) {
        // $tmp 字串在末尾增加一位，其内容为 $txt 的第 $i 位，
        // 与 $txt 的第 $i + 1 位取异或。然后 $i = $i + 1
        $tmp .= $txt[$i] ^ $txt[++$i];
    }
    // 返回 $tmp 的值作为结果
    return $tmp;
}

/**
 * Passport 密匙处理函数
 *
 * @param        string          待加密或待解密的字串
 * @param        string          私有密匙(用于解密和加密)
 *
 * @return       string          处理后的密匙
 */
function passport_key($txt, $encrypt_key) {
    // 将 $encrypt_key 赋为 $encrypt_key 经 md5() 后的值
    $encrypt_key = md5($encrypt_key);
    // 变量初始化
    $ctr = 0;
    $tmp = '';
    // for 循环，$i 为从 0 开始，到小于 $txt 字串长度的整数
    for ($i = 0; $i < strlen($txt); $i++) {
        // 如果 $ctr = $encrypt_key 的长度，则 $ctr 清零
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        // $tmp 字串在末尾增加一位，其内容为 $txt 的第 $i 位，
        // 与 $encrypt_key 的第 $ctr + 1 位取异或。然后 $ctr = $ctr + 1
        $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
    }
    // 返回 $tmp 的值作为结果
    return $tmp;
}

function addslashes_deep($value) {
    $value = is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    return $value;
}

function stripslashes_deep($value) {
    if (is_array($value)) {
        $value = array_map('stripslashes_deep', $value);
    } elseif (is_object($value)) {
        $vars = get_object_vars($value);
        foreach ($vars as $key => $data) {
            $value->{$key} = stripslashes_deep($data);
        }
    } else {
        $value = stripslashes($value);
    }

    return $value;
}

function todaytime() {
    return mktime(0, 0, 0, date('m'), date('d'), date('Y'));
}

function admin_date($date) {
    $ld = mktime(0, 0, 0, 1, 1, date("Y", time())); //年
    if ($date >= $ld) {
        $fdate = date('m-d H:i', $date);
    } else {
        $fdate = date('Y-m-d', $date);
    }
    return $fdate;
}

/**
 * 友好时间
 */
function sub_day($endday, $staday, $range = '') {
    $value = $endday - $staday;
    if ($value < 0) {
        return '';
    } elseif ($value >= 0 && $value < 59) {
        return ($value + 1) . "秒";
    } elseif ($value >= 60 && $value < 3600) {
        $min = intval($value / 60);
        return $min . "分钟";
    } elseif ($value >= 3600 && $value < 86400) {
        $h = intval($value / 3600);
        return $h . "小时";
    } elseif ($value >= 86400 && $value < 86400 * 30) {
        $d = intval($value / 86400);
        return intval($d) . "天";
    } elseif ($value >= 86400 * 30 && $value < 86400 * 30 * 12) {
        $mon = intval($value / (86400 * 30));
        return $mon . "月";
    } else {
        $y = intval($value / (86400 * 30 * 12));
        return $y . "年";
    }
}

/**
 * 时间格式变换
 */
function daterange($endday, $staday, $format = 'Y-m-d', $color = '', $range = 3) {
    $value = $endday - $staday;
    if ($value < 0) {
        return '';
    } elseif ($value >= 0 && $value < 59) {
        $return = ($value + 1) . "秒前";
    } elseif ($value >= 60 && $value < 3600) {
        $min = intval($value / 60);
        $return = $min . "分钟前";
    } elseif ($value >= 3600 && $value < 86400) {
        $h = intval($value / 3600);
        $return = $h . "小时前";
    } elseif ($value >= 86400) {
        $d = intval($value / 86400);
        if ($d > $range) {
            return date($format, $staday);
        } else {
            $return = $d . "天前";
        }
    }
//    if ($color) {
//        $return = "<span id=\"r_time\" style=\"color:{$color}\">" . $return . "</span>";
//    }
    return $return;
}

/**
 * 友好时间
 */
function fdate($time) {
    if (!$time) return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = time() - mktime(0, 0, 0, 0, 0, date('Y')); //年
    $md = time() - mktime(0, 0, 0, date('m'), 0, date('Y')); //月
    $byd = time() - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = time() - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = time() - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = time() - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = time() - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日 H:i', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = '今天' . date('H:i', $time);
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m-d H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m-d H:i', $time);
                break;
            default:
                $fdate = date('Y-m-d', $time);
                break;
        }
    }
    return $fdate;
}

function PA($data) {
    $data = str_replace('AM', '上午', $data);
    $data = str_replace('PM', '下午', $data);
    return $data;
}

/**
 * [ddate 时间差]
 */
function ddate($s, $e) {
    $starttime = strtotime($s);
    $endtime = strtotime($e);
    $startyear = date('Y', $starttime);
    $startmonth = date('m', $starttime);
    $endyear = date('Y', $endtime);
    $endmonth = date('m', $endtime);
    $return = '';
    $return_year = $endyear - $startyear;
    $return_month = $endmonth - $startmonth;
    if ($return_month < 0) {
        $return_month += 12;
        $return_year -= 1;
    }

    if ($return_year > 0) {
        $return .= $return_year . '年';
    }
    if ($return_month > 0) {
        $return .= $return_month . '个月';
    }
    return $return;
}

/**
 * 对象转换成数组
 */
function object_to_array($obj) {
    $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
    foreach ($_arr as $key => $val) {
        $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
        $arr[$key] = $val;
    }
    return $arr;
}

/**
 * 获取图片
 */
function attach($attach, $type) {
    if (empty($attach)) return false;
    if (false === strpos($attach, 'http://') && false === strpos($attach, 'https://')) {
        //本地附件
        // return C('qscms_site_domain') . __ROOT__ . '/data/upload/' . $type . '/' . $attach.'?';
        return C('qscms_site_domain') . __ROOT__ . '/data/upload/' . $type . '/' . $attach.'?'.time();
        //远程附件
        //todo...
    } else {
        //URL链接
        return $attach;
    }
}

/**
 * 获取头像
 */
function avatar($user){
    if(empty($user)) return false;
    $user   = is_array($user) ? $user : M('Members')->where(['uid'=>$user])->find();
    $resume = M('Resume')->where(['uid'=>$user['uid']])->find();
    $avatar = !empty($resume['sex']) && $resume['sex']==2 ? 'default_w.png' : 'default_m.png';
    return !empty($user['avatars']) ? attach($user['avatars'], 'avatar') : attach($avatar, 'avatar');
}

/**
 * 获取图片
 */
function att($attach, $type) {
    if (empty($attach)) return false;
    if (false === strpos($attach, 'http://')) {
        //本地附件
        return '/data/upload/' . $type . '/' . $attach;
        //远程附件
        //todo...
    } else {
        //URL链接
        return $attach;
    }
}

/**
 * [badword 敏感词处理]
 * @param  [string] $data [文本内容]
 * @return [string]       [替换后的内容]
 */
function badword($data) {
    if (!C('qscms_badword_status')) return $data;
    //敏感词处理
    return D('Badword')->check($data);
}

/**
 * [requireone 验证数组内容必填一项：一维数组]
 */
function requireone($d) {
    $t = array_filter($d);
    return !empty($t);
}

/**
 * [ad 广告位初始化]
 * @param  [string] $tpl [广告位名称]
 * @return [html]        [广告位终端]
 * @return [num]         [广告数量]
 */
function ad($tpl, $num = '', $type = 'pc') {
    W('Common/Banner/index', array($tpl, $num, $type));
}

/**
 * [P 模板跳转 参数处理]
 * @param array $data [数组]
 */
function P($data = array()) {
    $get = $_GET;

    unset($get['_URL_']);
    unset($get['p']);
    unset($get['page']);
    if(strtolower(MODULE_NAME)!='admin'){
        foreach($get as $k=>$v){
            $k = strip_tags($k);
            $k=str_replace('>','',$k);
            $k=htmlspecialchars($k);
            $get[$k]=$v;
        }
    }
    return U(CONTROLLER_NAME . '/' . ACTION_NAME, array_merge($get, $data));
}

/*
    字段单独验证 
*/
function fieldRegex($value, $rule) {
    $validate = array(
        'require'  => '/.+/',
        'email'    => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
        'mobile'   => '/^(13|15|14|16|17|18|19)\d{9}$/',
        'tel'      => '/^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$/',
        'url'      => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
        'currency' => '/^\d+(\.\d+)?$/',
        'number'   => '/^\d+$/',
        'zip'      => '/^\d{6}$/',
        'integer'  => '/^[-\+]?\d+$/',
        'double'   => '/^[-\+]?\d+(\.\d+)?$/',
        'english'  => '/^[A-Za-z]+$/',
        'img'      => '(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/',
        'in'       => '/^(\d{1,10},)*(\d{1,10})$/',
        'qq'       => '/^[1-9]*[1-9][0-9]*$/',
        'user'	   => "/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u",//只能包含数字字母和汉字的名字只在utf-8下匹配
        'ym'       => '/^\d{4}$|^\d{4}-((0([1-9]))|(1(0|1|2)))$|^\d{4}-((0([1-9]))|(1(0|1|2)))-((0([1-9]))|([1-3]([0-9])))$/',//匹配年或者年月日
    );
    // 检查是否有内置的正则表达式
    if (isset($validate[strtolower($rule)]))
        $rule = $validate[strtolower($rule)];
    return preg_match($rule, $value) === 1;
}

function display_com_name($str)
{
    if(preg_match("/[\x{4e00}-\x{9fa5}]+/u", $str)) {
        //按照中文字符计算长度
        $len = mb_strlen($str, 'UTF-8');
        //echo '中文';
        if($len >= 3){
            //三个字符或三个字符以上掐头取尾，中间用*代替
            $str = mb_substr($str, 0, 1, 'UTF-8') . '****' . mb_substr($str, -1, 1, 'UTF-8');
        } elseif($len == 2) {
            //两个字符
            $str = mb_substr($str, 0, 1, 'UTF-8') . '****';
        }
    } else {
        //按照英文字串计算长度
        $len = strlen($str);
        //echo 'English';
        if($len >= 3) {
            //三个字符或三个字符以上掐头取尾，中间用*代替
            $str = substr($str, 0, 1) . '****' . substr($str, -1);
        } elseif($len == 2) {
            //两个字符
            $str = substr($str, 0, 1) . '****';
        }
    }

    return $str;
}


function contact_hide($data, $IsWhat = 2) {
    if ($IsWhat == 1) {
        return preg_replace('/([0[0-9]{2,3}[-]?[1-9]]|[1-9])[0-9]{2,4}([0-9]{3}[-]?[0-9]?)/i', '$1****$2', $data);
    } elseif ($IsWhat == 2) {
        return preg_replace('/(1[3456789]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $data);
    } elseif ($IsWhat == 3) {
        $email_array = explode("@", $data);
        $n = mb_strlen($email_array[0], 'utf-8');
        return str_pad(substr($email_array[0], 0, intval($n / 2)), $n, '*') . $email_array[1];
    }elseif ($IsWhat == -1){
           $str=$data;
        if(preg_match("/[\x{4e00}-\x{9fa5}]+/u", $str)) {
            //按照中文字符计算长度
            $len = mb_strlen($str, 'UTF-8');
            //echo '中文';
            if($len >= 3){
                //三个字符或三个字符以上掐头取尾，中间用*代替
                $str = mb_substr($str, 0, 1, 'UTF-8') . '某' . mb_substr($str, -1, 1, 'UTF-8');
            } elseif($len == 2) {
                //两个字符
                $str = mb_substr($str, 0, 1, 'UTF-8') . '某';
            }
        } else {
            //按照英文字串计算长度
            $len = strlen($str);
            //echo 'English';
            if($len >= 3) {
                //三个字符或三个字符以上掐头取尾，中间用*代替
                $str = substr($str, 0, 1) . '某' . substr($str, -1);
            } elseif($len == 2) {
                //两个字符
                $str = substr($str, 0, 1) . '某';
            }
        }
        return $str;
    }elseif ($IsWhat == -2){
        $str=$data;
        if(preg_match("/[\x{4e00}-\x{9fa5}]+/u", $str)) {
            //按照中文字符计算长度
            $len = mb_strlen($str, 'UTF-8');
            //echo '中文';
            if($len >= 3){
                //三个字符或三个字符以上掐头取尾，中间用*代替
                $str = mb_substr($str, 0, 1, 'UTF-8') . '**' . mb_substr($str, -1, 1, 'UTF-8');
            } elseif($len == 2) {
                //两个字符
                $str = mb_substr($str, 0, 1, 'UTF-8') . '**';
            }
        } else {
            //按照英文字串计算长度
            $len = strlen($str);
            //echo 'English';
            if($len >= 3) {
                //三个字符或三个字符以上掐头取尾，中间用*代替
                $str = substr($str, 0, 1) . '**' . substr($str, -1);
            } elseif($len == 2) {
                //两个字符
                $str = substr($str, 0, 1) . '**';
            }
        }
        return $str;
    }
    else {
        $n = mb_strlen($data, 'utf-8');
        $str = str_pad('', intval($n / 2), '*');
        return str_replace(substr($data, intval($n / 4), intval($n / 2)), $str, $data);
    }
}

/**
 * 记录职位和简历的刷新日志
 */
function write_refresh_log($data){
    $data['addtime'] = time();
    M('RefreshLog')->add($data);
}

/**
 * 写后台管理员日志（记录url信息）
 */
function admin_write_log($user) {
    $log['log_url'] = $_SERVER["REQUEST_URI"];
    $log['log_ip'] = get_client_ip();
    $Ip = new \Common\ORG\IpLocation('UTFWry.dat');
    $rst = $Ip->getlocation();
    $log['log_address'] = $rst['country'];
    $log['log_addtime'] = time();
    $log['operater_id'] = $user['id'];
    $log['operater'] = $user['username'];
    M('AdminLog')->add($log);
}

//会员操作日志、 管理员操作日志
function write_members_log($user, $type = '', $txt, $source = false, $params = array(), $operater_id = 0, $operater = '') {

    $members_log = $params;
    $members_log['log_uid'] = $user['uid'];
    $members_log['log_username'] = $user['username'];
    $members_log['log_addtime'] = time();
    $members_log['log_value'] = $txt;
    $members_log['log_ip'] = get_client_ip();
    $Ip = new \Common\ORG\IpLocation('UTFWry.dat');
    $rst = $Ip->getlocation();
    $members_log['log_address'] = $rst['country'];
    $members_log['log_utype'] = $user['utype'];
    $members_log['log_type'] = $type;

    if ($source) {
        $members_log['log_source'] = $source;
    } else if (C('LOG_SOURCE')) {
        $source = C('LOG_SOURCE');
        switch ($source) {
            case 2:
                $members_log['log_source'] = '触屏版';
                break;
            case 3:
                $members_log['log_source'] = '小程序';
                break;
            default:
                $members_log['log_source'] = '网页版';
                break;
        }
    } else {
        $members_log['log_source'] = '小程序';
    }
    $members_log['operater_id'] = $operater_id;
    $members_log['operater'] = $operater;
    D('MembersLog')->add($members_log);
    unset($members_log);
}

//截取字符
function cut_str($sourcestr, $cutlength, $start = 0, $dot = '') {
    $returnstr = '';
    $i = 0;
    $n = 0;
    $str_length = strlen($sourcestr);
    $mb_str_length = mb_strlen($sourcestr, 'utf-8');
    while (($n < $cutlength) && ($i <= $str_length)) {
        $temp_str = substr($sourcestr, $i, 1);
        $ascnum = ord($temp_str);
        if ($ascnum >= 224) {
            $returnstr = $returnstr . substr($sourcestr, $i, 3);
            $i = $i + 3;
            $n++;
        } elseif ($ascnum >= 192) {
            $returnstr = $returnstr . substr($sourcestr, $i, 2);
            $i = $i + 2;
            $n++;
        } elseif (($ascnum >= 65) && ($ascnum <= 90)) {
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i = $i + 1;
            $n++;
        } else {
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i = $i + 1;
            $n = $n + 0.5;
        }
    }
    if ($mb_str_length > $cutlength) {
        $returnstr = $returnstr . $dot;
    }
    return $returnstr;
}

// 分词
function get_tags($title, $num = 10, $mode = true, $s = false) {
    vendor('pscws4.pscws4#class');
    $pscws = new \PSCWS4();
    $pscws->set_dict(QSCMS_DATA_PATH . 'scws/dict.utf8.xdb');
    $pscws->set_rule(QSCMS_DATA_PATH . 'scws/rules.utf8.ini');
    $pscws->set_ignore(true);
    $pscws->send_text($title);
    $words = $pscws->get_tops($num);
    $tags = array();
    foreach ($words as $val) {
        $tags_one[] = $val['word'];
    }
    $pscws->close();
    if($mode){
        //开启二元分词
        foreach ($tags_one as $key => $value) {
            if($key == 0){
                $arr =  str_replace($value,'',$title);
            }else{
                $arr =  str_replace($value,'',$arr);
            }
        }
        if($arr){
            if(preg_match_all("/[\x{4e00}-\x{9fa5}]/u", $arr, $estr)){
                $count = count($estr[0]);
                foreach ($estr[0] as $key => $value) {
                    if($key+1 < $count){
                        $tags_two[] =$estr[0][$key].$estr[0][$key+1];
                    }
                }
            }
        }
    }
    if($tags_two){
        $tags =array_merge($tags_one,$tags_two);
    }else{
        $tags =$tags_one;
    }
    if(!$tags) $tags[] = $title;
    return $s ? $tags : array_map("fulltextpad", $tags);
}
/**
 * 前台分页统一
 */
function pager($count, $pagesize) {
    $pager = new Common\ORG\Page($count, $pagesize);
    $pager->rollPage = 5;
    $pager->setConfig('first', '首页');
    $pager->setConfig('prev', '上一页');
    $pager->setConfig('next', '下一页');
    $pager->setConfig('last', '最后一页');
    if (C('PLATFORM') == 'mobile') {
        $pager->setConfig('theme', '%upPage% <span>%nowPage%/%totalPage%</span> %downPage%');
    } else {
        $pager->setConfig('theme', '%first% %upPage% %linkPage% %downPage% %end% %jump_page%');
    }
    return $pager;
}

/**
 *  解析 url
 */
function parseUrl($data) {
    $parse_url = parse_url(parse_url_request_url());
    $parse_url = $parse_url['query'];
    parse_str($parse_url, $urlarray);
    foreach ($data as $key => $val) {
        $urlarray[$key] = $val;
    }
    return '?' . http_build_query($urlarray);
}

function parse_url_request_url() {
    if (isset($_SERVER['REQUEST_URI'])) {
        $url = $_SERVER['REQUEST_URI'];
    } else {
        if (isset($_SERVER['argv'])) {
            $url = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];
        } else {
            $url = $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
        }
    }
    return $url;
}

/**
 * [url_rewrite 伪静态]
 * @param  [type]    $alias     [description]
 * @param  [array]   $get       [传值]
 * @param  boolean $rewrite [是否开启伪静态]
 * @return [string]             [链接]
 */
function url_rewrite($alias = NULL, $get = NULL, $subsite_id = 0, $rewrite = true) {
    if(MODULE_NAME=='Appapi'){
        $page_list=F('appapi_page_list','',QSCMS_APPAPI_PATH);
        return U($page_list[$alias]['module'] . '/' . $page_list[$alias]['controller'] . '/' . $page_list[$alias]['action'], $get, true, false, true);
    }
    $page_list = D('Page')->page_cache();
    $url = $url_prefix = '';
    if ($get['key'] && C('qscms_key_urlencode') == 1) {
        $get['key'] = urlencode($get['key']);
    }
    $http_host = $_SERVER['HTTP_HOST'];
    if ($page_list[$alias]['url'] == '0' || $rewrite == false) {//原始链接
        $domain_rules = C('APP_SUB_DOMAIN_RULES');
        $sub_domain = $domain_rules[$http_host];
        if ($sub_domain) {
            strtolower($sub_domain) != strtolower($page_list[$alias]['module']) && $m = $page_list[$alias]['module'] . '/';
        } elseif (MODULE_NAME != C('DEFAULT_MODULE') || strtolower($page_list[$alias]['module']) != strtolower(MODULE_NAME)) {
            $m = $page_list[$alias]['module'] . '/';
        }
        if ($m) {
            $url = U($m . $page_list[$alias]['controller'] . '/' . $page_list[$alias]['action'], $get, true, false, true);
        } else {
            $url = U($page_list[$alias]['controller'] . '/' . $page_list[$alias]['action'], $get, true, false, true, true);
        }
    } else {
        if ($url = $page_list[$alias]['rewrite']) {
            if ($page_list[$alias]['pagetpye'] == '2' && empty($get['page'])) {
                $get['page'] = 1;
            }
            if ($get) {
                foreach ($get as $k => $val) {
                    $data['($' . $k . ')'] = $val;
                }
                $url = strtr($url, $data);
            }
            $url = preg_replace('/\(\$(\w+)\)/', '', $url);
            $url = __ROOT__ . '/' . $url . C('URL_HTML_SUFFIX');
        } else {
            $domain_rules = C('APP_SUB_DOMAIN_RULES');
            $sub_domain = $domain_rules[$http_host];
            if ($sub_domain) {
                strtolower($sub_domain) != strtolower($page_list[$alias]['module']) && $m = $page_list[$alias]['module'] . '/';
            } elseif (MODULE_NAME != C('DEFAULT_MODULE') || strtolower($page_list[$alias]['module']) != strtolower(MODULE_NAME)) {
                $m = $page_list[$alias]['module'] . '/';
            }
            if ($m) {
                $url = U($m . $page_list[$alias]['controller'] . '/' . $page_list[$alias]['action'], $get);
            } else {
                $url = U($page_list[$alias]['controller'] . '/' . $page_list[$alias]['action'], $get, true, false, false, true);
            }
        }
    }
    return $url_prefix . $url;
}

function redirect301($url) {
    send_http_status(301);
    redirect($url);
}

function redirect404() {
    $controller = new \Common\Controller\BaseController;
    $controller->_empty();
}

function https_request($url, $data = null) {
    if (function_exists('curl_init')) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    } else {
        return false;
    }
}

//百度链接提交
function baidu_submiturl($urls, $param) {
    $_SUBURL = D('BaiduSubmiturl')->get_cache();
    if ($_SUBURL['token'] && $_SUBURL[$param] == '1' && function_exists('curl_init')) {
        if (!is_array($urls)) {
            $urls = array($urls);
        }
        foreach ($urls as $key => $value) {
            if (stripos($value, 'http://') === false) {
                $urls[$key] = C('qscms_site_domain') . $value;
            }
        }
        $site_domain = str_replace('http://', '', C('qscms_site_domain'));
        $api = 'http://data.zz.baidu.com/urls?site=' . $site_domain . '&token=' . $_SUBURL['token'];
        $ch = curl_init();
        $options = array(
            CURLOPT_URL            => $api,
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS     => implode("\n", $urls),
            CURLOPT_HTTPHEADER     => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
    }
}

function convert_datefm($date, $format, $separator = "-") {
    if ($format == "1") {
        return date("Y-m-d", $date);
    } else {
        if (!preg_match("/^[0-9]{4}(\\" . $separator . ")[0-9]{1,2}(\\1)[0-9]{1,2}(|\s+[0-9]{1,2}(|:[0-9]{1,2}(|:[0-9]{1,2})))$/", $date)) return false;
        $date = explode($separator, $date);
        return mktime(0, 0, 0, $date[1], $date[2], $date[0]);
    }
}

/**
 * 删除目录
 */
function rmdirs($dir, $rm_self = false) {
    $d = dir($dir);
    while (false !== ($child = $d->read())) {
        if ($child != '.' && $child != '..') {
            if (is_dir($dir . '/' . $child)) {
                rmdirs($dir . '/' . $child, true);
            } else {
                unlink($dir . '/' . $child);
            }
        }
    }
    $d->close();
    $rm_self && rmdir($dir);
}

/**
 * 获取随机字符串
 */
function get_rand_char($num) {
    if (empty($num)) {
        return false;
    }
    $string = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $str = '';
    for ($i = 0; $i < $num; $i++) {
        $pos = rand(0, 51);
        $str .= $string{$pos};
    }
    return $str;
}

/**
 * 获取随机手机验证码
 */
function getmobilecode() {
    $rand = mt_rand(1000, 9999);
    return $rand;
}

/**
 * 获取子目录
 */
function getsubdirs($dir) {
    $subdirs = array();
    if (!$dh = opendir($dir)) return $subdirs;
    while ($f = readdir($dh)) {
        if ($f == '.' || $f == '..') continue;
        $path = $dir . '/' . $f;  //如果只要子目录名, path = $f;
        $subdir = $f;
        if (is_dir($path)) {
            $subdirs[] = $subdir;
        }
    }
    closedir($dh);
    return $subdirs;
}

/**
 * 生成excel
 */
function create_excel($top_str, $data) {
    header("Content-Type: application/vnd.ms-execl");
    header("Content-Disposition: attachment; filename=myExcel.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo $top_str;
    foreach ($data as $k => $v) {
        foreach ($v as $k1 => $v1) {
            echo $v1;
            echo ($k1 + 1) < count($v) ? "\t" : "";
        }
        echo "\t\n";
    }
}

/**
 *计算坐标点周围某段距离的正方形的四个点
 * @param lng float 经度
 * @param lat float 纬度
 * @param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为0.5千米
 * @return array 正方形的四个点的经纬度坐标
 */
function square_point($lng, $lat, $distance = 0.5) {
    $earth_radius = 6378.138;
    $dlng = 2 * asin(sin($distance / (2 * $earth_radius)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);
    $dlat = $distance / $earth_radius;
    $dlat = rad2deg($dlat);
    return array(
        'lt' => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng),
        'rt' => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng),
        'lb' => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng),
        'rb' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng)
    );
}

//检查缓存
function check_cache($cache, $dir, $days = 1) {
    $cachename = STATISTICS_PATH . $dir . $cache;
    if (!is_dir(STATISTICS_PATH . $dir)) mkdir(STATISTICS_PATH . $dir);
    if (!is_writable(STATISTICS_PATH . $dir)) {
        exit("请先将“" . STATISTICS_PATH . $dir . "”目录设置可读写！");
    }
    if (file_exists($cachename)) {
        $filemtime = filemtime($cachename);
        if ($filemtime > strtotime("-" . $days . " day")) {
            return file_get_contents($cachename);
        }
    }
    return false;
}

//写入缓存
function write_cache($cache, $dir, $json) {
    if (!is_dir(STATISTICS_PATH . $dir)) mkdir(STATISTICS_PATH . $dir);
    $cachename = STATISTICS_PATH . $dir . $cache;
    if (!file_put_contents($cachename, $json, LOCK_EX)) {
        $fp = @fopen($cachename, 'wb+');
        if (!$fp) {
            exit('生cache文件失败，请设置“' . STATISTICS_PATH . $dir . '”的读写权限');
        }
        if (!@fwrite($fp, $json)) {
            exit('生cache文件失败，请设置“' . STATISTICS_PATH . $dir . '”的读写权限');
        }
        @fclose($fp);
    }
}

/**
 * [get_first 后台取get传值第一个元素key及val]
 */
function get_first() {
    if (!$_GET) return '';
    foreach($_GET as $key=>$val){
        if($key != '_k_v') $get[$key] = $val;
    }
    return $get ? '&' . http_build_query($get) : '';
}

/**
 * 获取跳转到触屏的地址
 * $data = array(
 *      'c'=>'',
 *      'a'=>'',
 *      'params'=>'a=1&b=2&c=3',
 * );
 */
function build_mobile_url($data = array()) {
    $config = F('Mobile/Conf/config', '', APP_PATH);
    $url = C('qscms_site_domain') . C('qscms_site_dir');
    if (empty($data)) {
        if ($config['URL_MODEL'] == 0) {
            $url = C('qscms_wap_domain') ? C('qscms_wap_domain') : (C('qscms_site_domain') . C('qscms_site_dir') . '?m=Mobile');
        } else if ($config['URL_MODEL'] == 1) {
            $url = C('qscms_wap_domain') ? C('qscms_wap_domain') : (C('qscms_site_domain') . C('qscms_site_dir') . 'index.php/Mobile');
        } else if ($config['URL_MODEL'] == 2) {
            if(!C('subsite_info.s_id')){
                $url = C('qscms_wap_domain') ? C('qscms_wap_domain') : (C('qscms_site_domain') . C('qscms_site_dir') . 'Mobile');
            }else{
                if(C('subsite_info.s_m_domain')){
                    $url =C('subsite_info.mobile_type').C('subsite_info.s_m_domain');
                }else{
                    $url =C('subsite_info.pc_type').C('subsite_info.s_domain').C('qscms_site_dir').'?m=Mobile';
                }
                //$url ='http://'.$url;
            }

        }
    } else {
        if ($config['URL_MODEL'] == 0) {
            if (C('qscms_wap_domain')) {
                $url = C('qscms_wap_domain') . '?c=' . $data['c'] . '&a=' . $data['a'] . ($data['params'] ? ('&' . $data['params']) : '');
            } else {
                $url = C('qscms_site_domain') . C('qscms_site_dir') . '?m=Mobile&c=' . $data['c'] . '&a=' . $data['a'] . ($data['params'] ? ('&' . $data['params']) : '');
            }
        } else if ($config['URL_MODEL'] == 1) {
            if ($data['params']) {
                $data['params'] = str_replace("&", "/", $data['params']);
                $data['params'] = str_replace("=", "/", $data['params']);
            }
            if (C('qscms_wap_domain')) {
                $url = C('qscms_wap_domain') . '/index.php/' . $data['c'] . '/' . $data['a'] . ($data['params'] ? ('/' . $data['params']) : '');
            } else {
                $url = C('qscms_site_domain') . C('qscms_site_dir') . 'index.php/Mobile/' . $data['c'] . '/' . $data['a'] . ($data['params'] ? ('/' . $data['params']) : '');
            }
        } else if ($config['URL_MODEL'] == 2) {
            if ($data['params']) {
                $data['params'] = str_replace("&", "/", $data['params']);
                $data['params'] = str_replace("=", "/", $data['params']);
            }
            if(!C('subsite_info.s_id')){
                if (C('qscms_wap_domain')) {
                    $url = C('qscms_wap_domain') . '/' . $data['c'] . '/' . $data['a'] . ($data['params'] ? ('/' . $data['params']) : '');
                } else {
                    $url = C('qscms_site_domain') . C('qscms_site_dir') . 'Mobile/' . $data['c'] . '/' . $data['a'] . ($data['params'] ? ('/' . $data['params']) : '');
                }
            }else{
                if(C('subsite_info.s_m_domain')){
                    $url = C('subsite_info.mobile_type').C('subsite_info.s_m_domain'). '/' . $data['c'] . '/' . $data['a'] . ($data['params'] ? ('/' . $data['params']) : '');
                }else{
                    $url = C('subsite_info.pc_type').C('subsite_info.s_domain') . '/'. 'Mobile/' . $data['c'] . '/' . $data['a'] . ($data['params'] ? ('/' . $data['params']) : '');
                }

            }
        }
    }
    return $url;
}
//分站获取ip
function GetIp() {
    $realip = '';
    $unknown = 'unknown';
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($arr as $ip) {
                $ip = trim($ip);
                if ($ip != 'unknown') {
                    $realip = $ip;
                    break;
                }
            }
        } else if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else if (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
            $realip = $_SERVER['REMOTE_ADDR'];
        } else {
            $realip = $unknown;
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)) {
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)) {
            $realip = getenv("REMOTE_ADDR");
        } else {
            $realip = $unknown;
        }
    }
    $realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;
    return $realip;
}

function GetIpLookup($ip = '') {
    if (empty($ip)) {
        $ip = GetIp();
    }
    if($ip_info = S('ip_info_'.$ip)) return $ip_info;
    $ipcloude=\Common\qscmslib\ipcloud::ip();
    if($ipcloude!=false){
        $rst=$ipcloude;
    }else{
        $Ip = new \Common\ORG\IpLocation('UTFWry.dat');
        $rst = $Ip->getlocation();
    }
    if($rst){
        $obj['ip'] = $ip;
        $obj['country'] = $rst['country'];
        S('ip_info_'.$ip,$obj,86400);
    }else{
        return false;
    }
    return $obj;
}
//end
function del_punctuation($str) {
    if (!$str) return '';
    $char = "`·。、！？：；﹑•＂…‘’“”〝〞∕¦‖—　〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔！¡？¿﹖﹌﹏﹋＇´ˊˋ―﹫︳︴¯＿￣﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼（）";
    $pattern = array(
        "/[[:punct:]]/i",
        '/[' . $char . ']/u',
        '/[ ]{2,}/'
    );
    $str = preg_replace($pattern, '', $str);
    return $str;
}

function multimerge($a, $b) {
    if (is_array($b) && count($b)) {
        foreach ($b as $k => $v) {
            if (is_array($v) && count($v)) {
                $a[$k] = in_array($k, array('SESSION_OPTIONS')) ? multimerge($a[$k], $v) : $v;
            } else {
                $a[$k] = $v;
            }
        }
    } else {
        $a = $b;
    }
    return $a;
}

function emoji_unicode($str) {
    $str = json_encode($str);
    $str = preg_replace("#(\\\(ue|ud)[0-9a-f]{3})#ie", "addslashes('\\1')", $str);
    $str = json_decode($str);
    return $str;
}

function unicode_emoji($str) {
    $str = preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2','UTF-8', pack('H4', '\\1'))", $str);
    return $str;
}

function _I($data) {
    if (C('DEFAULT_FILTER')) {
        $filters = explode(',', C('DEFAULT_FILTER'));
        foreach ($filters as $filter) {
            $data = is_array($data) ? array_map($filter, $data) : $filter($data);
        }
    }
    return $data;
}

/**
 * 查询手机号归属地
 */
function get_mobile_address($mobile) {
    $url = 'https://www.74cms.com/index.php?m=Home&c=Plus&a=get_mobile_address&mobile=' . $mobile;
    $result = https_request($url);
    $result_arr = json_decode($result, true);
    if ($result_arr['status'] == 1) {
        return $result_arr['data'];
    } else {
        return false;
    }
}

/**
 * [get_city_info 获取地区信息(地区id组合，地区中文组合)]
 */
function get_city_info($ids) {
   // var_dump($ids);die;
    if (!$ids) return array('district' => '', 'district_cn' => '');
    $city = D('CategoryDistrict')->get_district_cache('all');
    if (false === $city_cate = F('city_search_cate')) $city_cate = D('CategoryDistrict')->city_search_cache();
    $spell = D('CategoryDistrict')->city_cate_cache();
    foreach (explode(',', $ids) as $val) {

        $areas  = explode('_', $city_cate[$val]);
        $a = array_filter($areas);
        $c = count($a);
        if (!$c) {
            continue;
        } elseif ($c == 1) {
            $district_cn[] = $city[0][$a[0]];
        } elseif ($c > 1) {
            $district_cn[] = $city[$a[$c - 2]][$a[$c - 1]];
        }
        foreach ($a as $key => $v) {
            $b[] = $key == 0 ? $city[0][$v] : $city[$a[$key - 1]][$v];
            $s[] = $spell['id'][$v]['spell'];
        }
        $district_cn_all[] = implode('/', $b);
        $district[] = implode('.', $areas);
        $district_spell[] = implode('.', $s);
    }
    return array('district' => implode(',', $district), 'district_cn_all' => implode(',', $district_cn_all), 'district_cn' => implode(',', $district_cn), 'district_spell' => implode(',', $district_spell));
}
function randstr($length=6,$special=true){
    $hash='';
    $chars= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    $special && $chars .= '@#!~?:-=';
    $max=strlen($chars)-1;
    mt_srand((double)microtime()*1000000);
    for($i=0;$i<$length;$i++)   {
        $hash.=$chars[mt_rand(0,$max)];
    }
    return $hash;
}
function resume_refreshtime_day($refreshtime){
    $day = intval((time()-$refreshtime) / 86400);
    if($day < 1){
        $val = 1;
    }elseif($day < 3){
        $val = 3;
    }elseif($day < 5){
        $val = 5;
    }else{
        $val = 0;
    }
    return intval(C('qscms_resume_download_points_conf.'.$val));
}
function verify_mobile($mobile,$smsVerify,$vcode_sms){
    if(!$vcode_sms) return '请输入验证码！';
    $verify_num = session('_verify_num_check');
    if($verify_num >= C('VERIFY_NUM_CHECK')) return '非法操作！';
    if(!fieldRegex($mobile, 'mobile')) return '手机号格式错误！';
    if(!$smsVerify) return '短信验证码错误！';
    if($mobile != $smsVerify['mobile']) return '手机号不一致！';
    if(time() > $smsVerify['time'] + 600) return '短信验证码已过期！';
    $mobile_rand = substr(md5($vcode_sms), 8, 16);
    if($mobile_rand != $smsVerify['rand']){
        session('_verify_num_check',++$verify_num);
        return '短信验证码错误！';
    }
    session('_verify_num_check',null);
    return true;
}

/**
 * 地址转换
from:
1：GPS设备获取的角度坐标，WGS84坐标;
2：GPS获取的米制坐标、sogou地图所用坐标;
3：google地图、soso地图、aliyun地图、mapabc地图和amap地图所用坐标，国测局（GCJ02）坐标;
4：3中列表地图坐标对应的米制坐标;
5：百度地图采用的经纬度坐标;
6：百度地图采用的米制坐标;
7：mapbar地图坐标;
8：51地图坐标

to:
3：国测局（GCJ02）坐标;
4：3中对应的米制坐标;
5：bd09ll(百度经纬度坐标);
6：bd09mc(百度米制经纬度坐标)
 */
function change_coords($location_arr,$from,$to){
    $url = 'http://api.map.baidu.com/geoconv/v1/?coords=';
    $coords_arr = array();
    foreach ($location_arr as $key => $value) {
        $coords_arr[] = $value;
    }
    $url .= implode(";", $coords_arr);
    $url .= '&from='.$from.'&to='.$to.'&ak='.C('qscms_map_ak');
    $result = https_request($url);
    $result_arr = json_decode($result,1);
    if($result_arr['status']==0){
        return array('status'=>1,'data'=>$result_arr['result']);
    }else{
        return array('status'=>0);
    }
}
/**
 * 生成随机浮点数
 */
function random_float($min = 0, $max = 1) {
    $rand = $min + mt_rand() / mt_getrandmax() * ($max - $min);
    return round($rand,2);
}
function unique_str($str) {
    $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    $key = "74cms";
    $strhash = md5($key . $str);
    $len = strlen($strhash);

    #将加密后的串分成4段，每段4字节，对每段进行计算，一共可以生成四组短连接
    for ($i = 0; $i < 4; $i++) {
        $strhash_piece = substr($strhash,  $i * $len / 4, $len / 4);
        #将分段的位与0x3fffffff做位与，0x3fffffff表示二进制数的30个1，即30位以后的加密串都归零
        $hex = hexdec($strhash_piece) & 0x3fffffff; #此处需要用到hexdec()将16进制字符串转为10进制数值型，否则运算会不正常

        $encript_str = "";
        #生成6位短连接
        for ($j = 0; $j < 6; $j++) {
            #将得到的值与0x0000003d,3d为61，即charset的坐标最大值
            $encript_str .= $charset[$hex & 0x0000003d];
            #循环完以后将hex右移5位
            $hex = $hex >> 5;
        }

        $encript_str_list[] = $encript_str;
    }
    return $encript_str_list[0];
}
/**
 * [changeToBaidu 转换为百度经纬度]
 * @param  [type] $lat [description]
 * @param  [type] $lng [description]
 * @return [type]      [description]
 * @author zhiai 2020/11/16 11:20
 */
function changeToBaidu($lat, $lng)
{
    $apiurl = 'http://api.map.baidu.com/geoconv/v1/?coords=' . $lng . ',' . $lat . '&from=1&to=5&ak=4c1bb2055e24296bbaef36574877b4e2';
    $file = file_get_contents($apiurl);
    $arrpoint = json_decode($file, true);
    //  var_dump($arrpoint);
    return $arrpoint['result'][0];
}

/**
 * [getRealyAddress 获取具体位置]
 * @param  [type] $lat [纬度]
 * @param  [type] $lng [经度]
 * @return [type]      [description]
 * @author zhiai 2020/11/16 11:20
 */
function getRealyAddress($lat, $lng)
{
    $address = '';
    if ($lat && $lng) {
        $arr = changeToBaidu($lat, $lng);
        // var_dump($arr);
        $url = 'http://api.map.baidu.com/geocoder/v2/?callback=&location=' . $arr['y'] . ',' . $arr['x'] . '.&output=json&pois=1&ak=4c1bb2055e24296bbaef36574877b4e2';
        $content = file_get_contents($url);
        $place = json_decode($content, true);
        $address = $place['result']['addressComponent']['city'];
    }
    //   var_dump($place);
// var_dump($address);die;
    return $address;
}

function sendMail($to, $title, $content,$path='',$name='',$fujian_one='',$fujian_two='',$email='') {

    Vendor('PHPMailer.PHPMailerAutoload');
    $mail = new PHPMailer(); //实例化
    $mail->CharSet      = "UTF-8";                     //设定邮件编码
    $mail->SMTPDebug    = 0;                        // 调试模式输出
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host         ='smtp.163.com'; //smtp服务器的名称（这里以QQ邮箱为例）
    $mail->SMTPAuth     = true; //启用smtp认证
    $mail->Username     = 'gcq_notice@163.com'; //你的邮箱名
    $mail->Password     = 'WYTUZUOCERRMANBT' ; //邮箱密码
    $mail->Port         = 25;  // 服务器端口 25 或者465 具体要看邮箱服务器支持

    $mail->From         = 'gcq_notice@163.com'; //发件人地址（也就是你的邮箱地址）
    $mail->FromName     = '工程桥人才网'; //发件人姓名
    $mail->AddAddress($to,"尊敬的客户");//收件人地址
    $mail->WordWrap     = 50; //设置每行字符长度
    $mail->IsHTML(true); // 是否HTML格式邮件
    $mail->Subject      = $title; //邮件主题

    $mail->Body         = $content; //邮件内容
    $mail->AltBody      = "当前发送的验证码为：654321"; //邮件正文不支持HTML的备用显示
 //var_dump($fujian_two);
  //  var_dump($fujian_one);die;
    $mail->addAttachment($fujian_one,'附件简历1.xls'); // 添加附件,并指定名称
    $mail->addAttachment($fujian_two,'附件简历2.xls'); // 添加附件,并指定名称
  //  $mail->addAttachment(iconv('utf-8', 'gb2312', $path),$name);
    return($mail->Send());
}


function sendSms($mobile, $rands=array(), $type) {
    $setting    = array(
        'appkey'    => 'AKID1OaWDoIjrnSouJyePwJQ05nFQBgruHel',
        'secretKey' => '0yg9LIyOZTCK4XkgNt9ObYFZAYgZBRTy',
    );
    $templateId = [
        'reg_'      => 805673,//注册
        'login_'    => 805673,//登陆
        'mpw_'      => 805673,//修改密码
        'mtel_'     => 805673,//修改手机号
        'mwithdraw_'=> 805673,//提现
        'mgcb_'     => 805673,//工程币支付验证
        'share_'    => 805673,//分享验证
    ];
    if(empty($templateId[$type])){
        return ['code'=>1, 'msg'=> '发送的短信类型不存在'];
    }
    $config =  D('Config')->config_cache();
    $ct = $config['qscms_sms_captcha_service'];
    include_once QSCMSLIB_PATH . "sms/{$ct}/{$ct}.class.php";

    $obj    = new \tencent_sms($setting);
    $res    = $obj->sms($mobile, $rands, $templateId[$type]);
    if($res['SendStatusSet'][0]['Code']=='Ok' && !empty($res['RequestId'])) {
        return  ['code'=>0, 'msg'=> 'ok'];
    }else{
        return  ['code'=>1, 'msg'=> $res['SendStatusSet'][0]['Message']];
    }

}
/**
 * 生成顾问二维码
 * @param $url
 * @param $img
 */
function creat_qrcode($url,$img)
{
    $errorCorrectionLevel = 'L';//容错级别
    $matrixPointSize = 6;//生成图片大小
    //生成二维码图片
    Vendor('phpqrcode.phpqrcode');
    $qrcode = new \QRcode();
    $qrcode::png($url, 'qrcode.png', $errorCorrectionLevel, $matrixPointSize, 2);
    $logo = $img;//准备好的logo图片
    $QR = 'qrcode.png';//已经生成的原始二维码图
    if ($logo !== FALSE) {
        $QR = imagecreatefromstring(file_get_contents($QR));
        $logo = imagecreatefromstring(file_get_contents($logo));
        $QR_width = imagesx($QR);//二维码图片宽度
        $QR_height = imagesy($QR);//二维码图片高度
        $logo_width = imagesx($logo);//logo图片宽度
        $logo_height = imagesy($logo);//logo图片高度
        $logo_qr_width = $QR_width / 3;
        $scale = $logo_width/$logo_qr_width;
        $logo_qr_height = $logo_height/$scale;
        $from_width = ($QR_width - $logo_qr_width) /2;
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
    }
    $path='./data/upload/guwen/'.date('Y-m-d').'/';
    if(!file_exists($path)){
        mkdir($path,0777,true);
    }
    $path=$path.date('YmdHis').'.png';
    imagepng ( $QR, $path); //带Logo二维码的文件名);

    return $path;
}

/**
 * 添加用户套餐使用记录
 * @param $uid string 用户id
 * @param $use_type string  使用类型  gcb 工程币  taocan  套餐
 * @param $order_type string resume_down 下载  fa_bu  发布职位  guwen_server  顾问服务 buy 购买套餐
 * @param $price string  价格
 * @param $rid string 简历id
 * @param  $desc string 描述
 * @param  $job_id string 职位id
 * @param  $taocan_id string 套餐id
 */

function add_member_log($uid,$use_type,$order_type,$price,$rid,$desc='',$job_id=0,$taocan_id=0)
{

    $res=M('member_use_log')->add([
        'use_type'=>$use_type,
        'order_type'=>$order_type,
        'price'=>$price,
        'rid'=>$rid,
        'add_time'=>date('Y-m-d H:i:s',time()),
        'uid'=>$uid,
        'desc'=>$desc,
        'job_id'=>$job_id,
        'add_type'=>1,
        'taocan_id'=>$taocan_id
    ]);
    //  var_dump(M('member_use_log')->getLastSql());die;
    return $res;
}


function birthdayToAge($birthday){
    $age = strtotime($birthday);
    if($age === false){
        return false;
    }
    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
    $now = strtotime("now");
    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
    $age = $y2 - $y1;
    if((int)($m2.$d2) < (int)($m1.$d1))
        $age -= 1;
    return $age;
}

/**
 * 获取价格 入职费用
 * @param $jobs_info 职位信息
 * @param $type 发布类型
 * @return mixed
 */
function seal_month_price($jobs_info,$type=0)
{
    $id=$jobs_info['wage_id'];
    $jobs_id=$jobs_info['id'];
    // var_dump($jobs_info);die;

    $fa_type=$type;
    $xi_shu=$jobs_info['xishu_rate'];
    // $xi_shu=0;
    //  $fa_type=2;//
//    $zhao_type=1;
//    $jobs_id=51;

    $jobs_info=M('jobs')->where(['id'=>$jobs_id])->find();
    if($fa_type){
        $jobs_info['fa_type']=$fa_type;
    }else{
        $fa_type=$jobs_info['fa_type'];
    }
    //  var_dump($jobs_info);die;
    $zhao_type=$jobs_info['old_zhao_type_id'];
    $qs_wage = D('Category')->category_wage();//薪资
    $price_info=$qs_wage[$id];
    $price_info=explode('-',$price_info);
    $di_price=$price_info[0];
    $gao_price=$price_info[1];
    $avg_price=(($di_price+$gao_price)/2)*1000;
    $data['di_price']=$di_price;  //最低
    $data['gao_price']=$gao_price;//最高
    $data['avg_price']=$avg_price;//平均薪资
    // 发布类型 发布类型 发布类型 0 未发布成功 1 常规 2 顾问找人才 3 悬赏找人才    4 顾问推荐

    switch ($fa_type){
        case 2 :
            if($zhao_type==1 || $zhao_type==2){  //常规
                $ru_zhi=$avg_price*0.3*0.5;
                $ru_zhi_month=$avg_price*0.3*0.5;
                $service=$avg_price*0.3;
            }elseif ($zhao_type==3){//短期
                if($jobs_info['xm_day']>=90 || $jobs_info['xm_day']==0){
                    $ru_zhi=$avg_price*0.3*0.3;
                    $ru_zhi_month=$avg_price*0.3*0.7;
                    $service=$avg_price*0.3;
                }else{
                    $ru_zhi=$jobs_info['yi_kou_price']*0.5;
                    $ru_zhi_month=$jobs_info['yi_kou_price']*0.5;
                    $service=$jobs_info['yi_kou_price'];
                }
            }elseif ($zhao_type==4){ //项目
                if($jobs_info['xm_day']>=90 || $jobs_info['xm_day']==0){
                    $ru_zhi=$avg_price*0.3*0.3;
                    $ru_zhi_month=$avg_price*0.3*0.7;
                    $service=$avg_price*0.3;
                }else{
                    $ru_zhi=$jobs_info['yi_kou_price']*0.5;
                    $ru_zhi_month=$jobs_info['yi_kou_price']*0.5;
                    $service=$jobs_info['yi_kou_price'];
                }
                // var_dump($service);die;
            }
            break;
        case 3 :
            if($zhao_type==1 || $zhao_type==2){  //常规
                $ru_zhi=$avg_price*0.3*$jobs_info['xishu_rate']*0.5;
                $ru_zhi_month=$avg_price*0.3*$jobs_info['xishu_rate']*0.5;
                $service=$avg_price*0.3;

            }elseif ($zhao_type==3){//短期

                if($jobs_info['xm_day']>=90 || $jobs_info['xm_day']==0){
                    $ru_zhi=$avg_price*0.3*$jobs_info['xishu_rate']*0.3;
                    $ru_zhi_month=$avg_price*$jobs_info['xishu_rate']*0.3*0.7;
                    $service=$avg_price*0.3;
                }else{
                    $ru_zhi=$jobs_info['yi_kou_price']*0.5;
                    $ru_zhi_month=$jobs_info['yi_kou_price']*0.5;
                    $service=$jobs_info['yi_kou_price'];
                }
            }elseif ($zhao_type==4){ //项目
                if($jobs_info['xm_day']>=90 || $jobs_info['xm_day']==0){
                    $ru_zhi=$avg_price*0.3*$jobs_info['xishu_rate']*0.3;
                    $ru_zhi_month=$avg_price*0.3*$jobs_info['xishu_rate']*0.7;
                    $service=$avg_price*0.3;
                }else{
                    $ru_zhi=$jobs_info['yi_kou_price']*$jobs_info['xishu_rate']*0.5;
                    $ru_zhi_month=$jobs_info['yi_kou_price']*$jobs_info['xishu_rate']*0.5;
                    $service=$jobs_info['yi_kou_price'];
                }
            }
            break;
        case 4:
            if($zhao_type==1 || $zhao_type==2){  //常规
                $ru_zhi=$avg_price*0.3*0.5;
                $ru_zhi_month=$avg_price*0.3*0.5;
                $service=$avg_price*0.3;
            }elseif ($zhao_type==3){//短期

                if($jobs_info['xm_day']>=90 || $jobs_info['xm_day']==0){
                    $ru_zhi=$avg_price*0.3*0.3;
                    $ru_zhi_month=$avg_price*0.3*0.7;
                    $service=$avg_price*0.3;
                }else{
                  //  var_dump($avg_price);die;
//                     var_dump($jobs_info['yi_kou_price']);
//                     var_dump($jobs_info['xishu_rate']);die;
                    $ru_zhi=$jobs_info['yi_kou_price']*0.5;
                    $ru_zhi_month=$jobs_info['yi_kou_price']*0.5;
                    $service=$jobs_info['yi_kou_price'];
                }
            }elseif ($zhao_type==4){ //项目
                if($jobs_info['xm_day']>=90 || $jobs_info['xm_day']==0){
                    $ru_zhi=$avg_price*0.3*0.3;
                    $ru_zhi_month=$avg_price*0.3*0.7;
                    $service=$avg_price*0.3;
                }else{
                    $ru_zhi=$jobs_info['yi_kou_price']*0.5;
                    $ru_zhi_month=$jobs_info['yi_kou_price']*0.5;
                    $service=$jobs_info['yi_kou_price'];
                }
            }
            break;
    }
    $data['ru_zhi']=$ru_zhi;
    $data['ru_zhi_month']=$ru_zhi_month;
    $data['service_money']=$service;
    $data['yi_kou_price']=$jobs_info['yi_kou_price'];
    $data['avg_price']=$avg_price;
    return $data;
}


/**
 * 添加顾问收入金额
 * @param int $uid  用户id
 * @param string $money 金额
 * @param string $desc 描述
 * @param string $order_type 类型类型  down_resume 下载简历 servuice 保证金 withdraw 提现
 * @param int $down_type 下载类型  下载类型2 搜索 1 订单
 * @param int $fa_type   发布类型
 * @param int $rid      简历id
 * @param int $jobs_id   职位id
 * @param int $order_id   订单id
 * @param string $info    详情
 * @param string $comp_uid    企业用户id
 * @param string $add_type    记录类型 1 其他 2我的推荐企业
 * @param string $ruzhi_type    录入类型 0 无  1 入职 2入职满月
 * @return bool|mixed
 */
function add_guwen_money($uid,$money,$desc,$order_type,$type=1,$down_type=0,$fa_type=0,$rid=0,$jobs_id=0,$order_id=0,$info='',$comp_uid=0,$all_money=0,$add_type=1,$ruzhi_type=0,$lu_uid='')
{
    $memebr_info=M('members')->where(['uid'=>$uid])->find();
   //   var_dump($memebr_info);die;
    if(empty($memebr_info || $money<=0)){
        return false;
    }
    $re=true;
   // var_dump($order_type);die;
    if($add_type!=2){
        if($order_type!='withdraw'){
            $re=M('members')->where(['uid'=>$uid])->setInc('money',$money);
         //   var_dump(M('members')->getLastSql());
        }
        $memebr_info=M('members')->where(['uid'=>$uid])->find();
        $current_money=$memebr_info['money'];
    }else{
        $re=M('members')->where(['uid'=>$uid])->setInc('tui_com_money',$money);
        $memebr_info=M('members')->where(['uid'=>$uid])->find();
        $current_money=$memebr_info['tui_com_money'];
    }
//     var_dump($add_type);
//     var_dump($re);die;
    if($re){
        return  M('guwen_money_log')->add([
            'order_type'=>$order_type,
            'down_type'=>$down_type,
            'desc'=>$desc,
            'fa_type'=>$fa_type,
            'add_time'=>NOW_TIME,
            'gw_uid'=>$uid,
            'jobs_id'=>$jobs_id,
            'rid'=>$rid,
            'order_id'=>$order_id,
            'info'=>$info,
            'money'=>$money,
            'current_money'=>$current_money,
            'type'=>$type,
            'comp_uid'=>$comp_uid,
            'all_money'=>$all_money,
            'add_type'=>$add_type,
            'ruzhi_type'=>$ruzhi_type,
            'lu_uid'=>$lu_uid,
        ]);
    }
    return false;
}

/**
 * 获取微信用户信息
 * @param array $wxUserInfo 微信登陆信息
 * @return mixed
 */
function wxUserInfo($wxUserInfo) {
    if(empty($wxUserInfo['code']) || empty($wxUserInfo['encryptedData']) || empty($wxUserInfo['iv']) || empty($wxUserInfo['encryptedData_mobile']) || empty($wxUserInfo['iv_mobile'])){
        return ['status'=> 1, 'msg'=>'微信用户信息不全，请提交完整的微信授权信息'];
    }


    $response = WxFunction::getOauthOrization($wxUserInfo['code']);
    if ($response == false && empty($response['data']['session_key'])) {
        return ['status'=> 1, 'msg'=>'微信sessionkey换取失败'];
    }

    $wxdata     = array();
    $errCode    = WxFunction::decryptData($wxUserInfo['encryptedData'], $wxUserInfo['iv'], $response['data']['session_key'], $wxdata);
    $wxdata     = get_object_vars(json_decode($wxdata));
    if ($errCode == false || empty($wxdata['openId'])) {
        return ['status'=> 1, 'msg'=>'获取用户信息失败'];
    }

    $mobileDate     = array();
    $errCodeMobile  = WxFunction::decryptData($wxUserInfo['encryptedData_mobile'], $wxUserInfo['iv_mobile'], $response['data']['session_key'], $mobileDate);
    $mobileDate     = get_object_vars(json_decode($mobileDate));
    if ($errCodeMobile == false || empty($mobileDate['phoneNumber'])) {
        return ['status'=> 1, 'msg'=>'获取用户手机信息失败'];
    }

    return ['status'=>0, 'data'=>['wxdata'=>$wxdata, 'mobileData'=>$mobileDate]];
}

/**
 * 获取微信用户openid
 * @param string $code 小程序code\
 * @param int    $uid  用户uid
 * @return mixed
 */
function wxOpenId($code, $uid=0) {
    //if(!empty($uid) && S('openid_'.$uid)) return ['status'=>0, 'data'=>S('openid_'.$uid)];

    if(empty($code)){
        return ['status'=> 1, 'msg'=>'微信code信息不能为空'];
    }

    $response = WxFunction::getOauthOrization($code);
    if ($response == false || empty($response['data']['session_key'])) {
        return ['status'=> 1, 'msg'=>'微信sessionkey换取失败'];
    }

    //S('openid_'.$uid, $response['data']['openid']);

    return ['status'=>0, 'msg'=>'ok', 'data'=>$response['data']['openid']];
}


/**
 * 启动现金支付
 * @param string    $htype_cn          支付类型名称cn
 * @param string    $order_pay_type    订单支付类型  详见OrderModel $order_type  17升级人才顾问
 * @param string    $openid            用户openid
 * @param string    $payment_name      支付方式 这里只有微信支付
 * @param string    $amount            支付金额
 * @param int       $is_deductible     是否积分支付
 * @param int       $deductible        积分数量
 * @param array     $params            其余参数
 */
function call_cash_pay($htype_cn, $order_pay_type, $openid, $payment_name = 'wxpay', $amount = '0.0', $is_deductible = 0, $deductible = 0, $params = '') {
    $paymenttpye = D('Payment')->get_payment_info($payment_name);
    if (!$paymenttpye) return ['status'=> 1, 'msg'=>'支付方式错误'];

    //如果积分抵扣为0这抵扣分也为0
    if ($is_deductible == 0) $deductible = 0;

    if ($deductible > 0 && $deductible > $this->my_points) {
        return ['status'=> 1, 'msg'=>C('qscms_points_byname') . '不足，请使用其他方式支付！'];
    }

    if ($deductible > 0) {//当前金额减去扣除积分除以积分比例
        $m_amount = $amount - floatval($deductible / C('qscms_payment_rate'));
    } else {
        $m_amount = $amount;
    }


    $paysetarr['ordtotal_fee'] = $m_amount;
    $description = '购买服务：' . $htype_cn. ';' . $paymenttpye['byname'] . $paysetarr['ordtotal_fee'];

    if ($deductible > 0) {
        $description .= ';' . C('qscms_points_byname') . '支付：' . $deductible . C('qscms_points_byname');
    }

    //获取原来的订单号，如果不存在则添加
    $unparams = unserialize($params);
    $adds   = 0;
    if(!empty($unparams['jobs_id'])){

        $orderWhere = ['uid'=>C('visitor')['uid'], 'order_type'=>$order_pay_type, /*'pay_type'=>2, 'is_paid'=>1, /*'payment'=>$payment_name,*/ 'jobs_id'=>$unparams['jobs_id']];
        $order      = M('Order')->where($orderWhere)->find();

        if(!empty($order)) {
            $adds   = 1;
            $paysetarr['oid'] = strtoupper(substr($paymenttpye['typename'], 0, 1)) . "-" . date('ymd', time()) . "-" . date('His', time());

            M('Order')->where(['id' => $order['id']])->save(['oid'=>$paysetarr['oid'],'payment'=>'wxpay','payment_cn'=>'微信支付','is_paid'=>1,'amount' => $amount, 'pay_amount' => $paysetarr['ordtotal_fee'], 'fa_type'=>$unparams['fa_type']]);
            // $paysetarr['oid']   = $order['oid'];
            $insert_id          = $order['id'];

            //todo 加支付记录
        }

    }
    if($adds==0){
        //订单号
        $paysetarr['oid'] = strtoupper(substr($paymenttpye['typename'], 0, 1)) . "-" . date('ymd', time()) . "-" . date('His', time());

        $insert_id = D('Order')->add_order(C('visitor'), $paysetarr['oid'], $order_pay_type, $amount, $paysetarr['ordtotal_fee'], $deductible, $htype_cn, $payment_name, $paymenttpye['byname'], $description, time(), 1, 0, 0, 0, $params);
    }

    if ($deductible > 0 && $is_deductible == 1) {
        $log_payment = $paymenttpye['byname'] . '+' . C('qscms_points_byname') . '抵扣';
    } else {
        $log_payment = $paymenttpye['byname'];
    }
    write_members_log(C('visitor'), 'order', '创建增值服务订单（订单号：' . $paysetarr['oid'] . '），支付方式：' . $log_payment, false, array('order_id' => $insert_id));
    $paysetarr['payFrom'] = 'wx_mini';
   // $paysetarr['payFrom'] = 'pc';
    $paysetarr['type'] = $payment_name;
    $paysetarr['ordsubject'] = $htype_cn;
    $paysetarr['ordbody'] = $htype_cn;
    $paysetarr['openid'] = $openid;
    $r = D('Payment')->wx_pay($paysetarr);
    if(!$r['state']) return ['status'=> 1, 'msg'=>$r['msg']];
    if ($payment_name == 'wxpay') {
        $path = QSCMS_DATA_PATH . 'wxpay/';
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        fopen(QSCMS_DATA_PATH . 'wxpay/' . $paysetarr['oid'] . '.tmp', "w") or die("无法打开缓存文件!");
        $_SESSION['wxpay_no'] = $paysetarr['oid'];
        $r['insert_id']    = $insert_id;
        return ['status'=> 0, 'msg'=>'ok', 'data'=>$r];
        //$this->ajaxReturn(1, '回调成功', C('qscms_site_dir') . 'index.php?m=Home&c=Qrcode&a=index&url=' . $r['data']);
    }
}


/**
 * 启动现金支付
 * @param string    $htype_cn          支付类型名称cn
 * @param string    $order_pay_type    订单支付类型  详见OrderModel $order_type  17升级人才顾问
 * @param string    $openid            用户openid
 * @param string    $payment_name      支付方式 这里只有微信支付
 * @param string    $amount            支付金额
 * @param int       $is_deductible     是否积分支付
 * @param int       $deductible        积分数量
 * @param array     $params            其余参数
 */
function call_web_cash_pay($htype_cn, $order_pay_type, $openid, $payment_name = 'wxpay', $amount = '0.0', $is_deductible = 0, $deductible = 0, $params = '') {
    $paymenttpye = D('Payment')->get_payment_info($payment_name);
    if (!$paymenttpye) return ['status'=> 1, 'msg'=>'支付方式错误'];

    //如果积分抵扣为0这抵扣分也为0
    if ($is_deductible == 0) $deductible = 0;

    if ($deductible > 0 && $deductible > $this->my_points) {
        return ['status'=> 1, 'msg'=>C('qscms_points_byname') . '不足，请使用其他方式支付！'];
    }

    if ($deductible > 0) {//当前金额减去扣除积分除以积分比例
        $m_amount = $amount - floatval($deductible / C('qscms_payment_rate'));
    } else {
        $m_amount = $amount;
    }


    $paysetarr['ordtotal_fee'] = $m_amount;
    $description = '购买服务：' . $htype_cn. ';' . $paymenttpye['byname'] . $paysetarr['ordtotal_fee'];

    if ($deductible > 0) {
        $description .= ';' . C('qscms_points_byname') . '支付：' . $deductible . C('qscms_points_byname');
    }

    //获取原来的订单号，如果不存在则添加
    $unparams = unserialize($params);
    $adds   = 0;
    if(!empty($unparams['jobs_id'])){

        $orderWhere = ['uid'=>C('visitor')['uid'], 'order_type'=>$order_pay_type, /*'pay_type'=>2, 'is_paid'=>1, /*'payment'=>$payment_name,*/ 'jobs_id'=>$unparams['jobs_id']];
        $order      = M('Order')->where($orderWhere)->find();

        if(!empty($order)) {
            $adds   = 1;
            $paysetarr['oid'] = strtoupper(substr($paymenttpye['typename'], 0, 1)) . "-" . date('ymd', time()) . "-" . date('His', time());

            M('Order')->where(['id' => $order['id']])->save(['oid'=>$paysetarr['oid'],'payment'=>'wxpay','payment_cn'=>'微信支付','is_paid'=>1,'amount' => $amount, 'pay_amount' => $paysetarr['ordtotal_fee'], 'fa_type'=>$unparams['fa_type']]);
            // $paysetarr['oid']   = $order['oid'];
            $insert_id          = $order['id'];

            //todo 加支付记录
        }

    }
    if($adds==0){
        //订单号
        $paysetarr['oid'] = strtoupper(substr($paymenttpye['typename'], 0, 1)) . "-" . date('ymd', time()) . "-" . date('His', time());

        $insert_id = D('Order')->add_order(C('visitor'), $paysetarr['oid'], $order_pay_type, $amount, $paysetarr['ordtotal_fee'], $deductible, $htype_cn, $payment_name, $paymenttpye['byname'], $description, time(), 1, 0, 0, 0, $params);
    }

    if ($deductible > 0 && $is_deductible == 1) {
        $log_payment = $paymenttpye['byname'] . '+' . C('qscms_points_byname') . '抵扣';
    } else {
        $log_payment = $paymenttpye['byname'];
    }
    write_members_log(C('visitor'), 'order', '创建增值服务订单（订单号：' . $paysetarr['oid'] . '），支付方式：' . $log_payment, false, array('order_id' => $insert_id));
    // $paysetarr['payFrom'] = 'wx_mini';
    $paysetarr['payFrom'] = 'pc';
    $paysetarr['type'] = $payment_name;
    $paysetarr['ordsubject'] = $htype_cn;
    $paysetarr['ordbody'] = $htype_cn;
    $paysetarr['openid'] = $openid;
    $r = D('Payment')->wx_pay($paysetarr);
    if(!$r['state']) return ['status'=> 1, 'msg'=>$r['msg']];
    if ($payment_name == 'wxpay') {
        $path = QSCMS_DATA_PATH . 'wxpay/';
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        fopen(QSCMS_DATA_PATH . 'wxpay/' . $paysetarr['oid'] . '.tmp', "w") or die("无法打开缓存文件!");
        $_SESSION['wxpay_no'] = $paysetarr['oid'];
        $r['insert_id']    = $insert_id;
        return ['status'=> 0, 'msg'=>'ok', 'data'=>$r];
        //$this->ajaxReturn(1, '回调成功', C('qscms_site_dir') . 'index.php?m=Home&c=Qrcode&a=index&url=' . $r['data']);
    }
}








/**
 * 重新提交现金支付
 * @param string    $orderid           再次提交的订单ID
 * @param string    $openid            用户openid
 * @param string    $payment_name      支付方式 这里只有微信支付
 */
function resubmit_cash_pay($orderid, $openid, $payment_name = 'wxpay') {
    $paymenttpye = D('Payment')->get_payment_info($payment_name);
    if (!$paymenttpye) return ['status'=> 1, 'msg'=>'支付方式错误'];

    if (!$openid) return ['status'=> 1, 'msg'=>'微信openid不能为空'];

    $order  = M('Order')->where(['id'=>$orderid])->find();
    if(!$order) return ['status'=> 1, 'msg'=>'订单不存在'];

    if($order['is_paid']==2) return ['status'=> 1, 'msg'=>'当前订单已经成功支付过'];

    $log_payment = $paymenttpye['byname'];

    write_members_log(C('visitor'), 'order', '增值服务订单 重新提交（订单号：' . $order['oid'] . '），支付方式：' . $log_payment, false, array('order_id' => $order['id']));
    $paysetarr['ordtotal_fee']  = $order['pay_amount'];
    $paysetarr['oid']           = $order['oid'];
    $paysetarr['payFrom']       = 'wx_mini';
    $paysetarr['type']          = $payment_name;
    $paysetarr['ordsubject']    = $order['service_name'];
    $paysetarr['ordbody']       = $order['service_name'];
    $paysetarr['openid']        = $openid;
    $r = D('Payment')->wx_pay($paysetarr);
    if(!$r['state']) return ['status'=> 1, 'msg'=>$r['msg']];
    if ($payment_name == 'wxpay') {
        $path = QSCMS_DATA_PATH . 'wxpay/';
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        fopen(QSCMS_DATA_PATH . 'wxpay/' . $order['oid'] . '.tmp', "w") or die("无法打开缓存文件!");
        $_SESSION['wxpay_no'] = $paysetarr['oid'];
        $r['insert_id']    = $order['id'];
        return ['status'=> 0, 'msg'=>'ok', 'data'=>$r];
        //$this->ajaxReturn(1, '回调成功', C('qscms_site_dir') . 'index.php?m=Home&c=Qrcode&a=index&url=' . $r['data']);
    }
}



/**
 * 支付退款
 * @param string    $oid    原支付订单号
 * @param string    $roid   退款订单号
 * @param string    $amount   支付金额
 * @param string    $ramount   退款金额
 * @param string    $payResource  资源，便于异步回调判断处理
 */
function refund_pay($oid, $roid, $amount, $ramount, $payResource='') {
    $paysetarr['oid']       = $oid;
    $paysetarr['r_oid']     = $roid;
    $paysetarr['type']      = 'wxpay';
    $paysetarr['amount']    = $amount;
    $paysetarr['ordtotal_fee']    = $ramount;
    $paysetarr['pay_resource']    = $payResource;
    $r = D('Payment')->refund_pay($paysetarr);
    if(!$r['state']) return ['status'=> 1, 'msg'=>$r['msg']];

    $path = QSCMS_DATA_PATH . 'wxpay/';
    if (!is_dir($path)) {
        mkdir($path, 0777, true);
    }
    fopen(QSCMS_DATA_PATH . 'wxpay/' . $roid . '.tmp', "w") or die("无法打开缓存文件!");

    return ['status'=> 0, 'msg'=>'ok', 'data'=>$r];

}


/**
 * 下载简历添加顾问的余额
 * @param array $taocan_info 套餐信息
 * @param string $type 支付类型
 * @param string $uid   用户id
 * @param string $down_type 下载类型
 * @param string $rid   简历id
 * @param string $order_id  订单id
 */

function down_resume_get_guwen_money($taocan_info,$type,$uid,$down_type,$rid,$order)
{
    $all_price=M('config')->where(['name' => 'jl_download_money'])->getField('value');
    $order_id=$order['id'];
    if($type=='gcb'){
        if($taocan_info['price_rate']>0){
            $all_price=number_format($all_price*$taocan_info['price_rate']/100,2,'.','');
        }
    }elseif ($type=='use_taocan'){
        if($taocan_info['price_rate']>0){
            $all_price=number_format($all_price*$taocan_info['price_rate']/100,2,'.','');
        }
    }elseif ($type=='wxpay' || $type=='remittance'){
        $all_price=M('config')->where(['name' => 'jl_download_money'])->getField('value');
    }
    $order_info=M('order')->where(['id'=>$order_id])->find();
    //顾问获得的金额
    //查询当年前用户的顾问有几个
  //  var_dump($down_type);die;
    if($down_type==1){  //顾问推荐下载
        //$jobs_id=$order['jobs_id'];
        $info=unserialize($order['params']);
        $tui_jian_id=$info['tui_jian_id'];
        $tui_info=M('guwen_tui_jian_rusume')->where(['id'=>$tui_jian_id])->find();
        $row=M('members')->where(['uid'=>$tui_info['guwen_uid']])->find();
        $level_info=M('guwen_level')->where(['level'=>$row['advisor_level']])->find();
        $get_money=number_format($all_price*$level_info['jian_li_load_rate']/100,2);
        //查询当前顾问的等级    除以 顾问的总数
        add_guwen_money($tui_info['guwen_uid'],$get_money,'下载简历','down_resume',1,$down_type,0,$rid,0,$order_id,'下载简历增费用',$order_info['uid'],$get_money);
    }else{
        //主动搜索下载
        $guwen_infos=M('guwen_user')->where(['uid'=>$uid,'status'=>0])->select();
        $count=count($guwen_infos);
        //        var_dump($uid);die;
        //         var_dump($count);die;
        foreach($guwen_infos as $k=>$v){
            $row=M('members')->where(['uid'=>$v['guwen_id']])->find();
            $level_info=M('guwen_level')->where(['level'=>$row['advisor_level']])->find();
            $get_money=number_format($all_price*$level_info['jian_li_load_rate']/100/$count,2);
            //查询当前顾问的等级    除以 顾问的总数
            add_guwen_money($v['guwen_id'],$get_money,'下载简历','down_resume',1,$down_type,0,$rid,0,$order_id,'下载简历增费用',$order_info['uid'],$get_money);
        }
    }

    return true;
}

/**
 * 修改职位结束时间
 * @param array $zhao_end_time
 * @param array $order_info
 */
function edit_zhao_end_time($zhao_end_time=[],$order_info=[])
{
    //已经支付成功了 那就修改is_edit 为0  is_shou  为 o   is_again 为0

    //判断是否有套餐
   // $zhao_end_time='';
    $order_info=M('order')->where(['id'=>$order_info['id']])->find();
    $taocan_info=D('MembersSetgcb')->get_user_setmeal($order_info['uid']);
    $jobs_info=M('jobs')->where(['id'=>$order_info['jobs_id']])->find();
    // var_dump($zhao_end_time);die;
    if($taocan_info && empty($zhao_end_time)){
        if(!$jobs_info['is_edit']){
            M('jobs')->where(['id'=>$order_info['jobs_id']])->setField('zhao_end_time',date('Y-m-d',strtotime('+1 year')));
        }else{
            if($jobs_info['is_shou']){
                M('jobs')->where(['id'=>$order_info['jobs_id']])->setField('zhao_end_time',date('Y-m-d',strtotime('+1 year')));
            }
        }
    }
    if(empty($taocan_info) && empty($zhao_end_time)){
        //判断发布类型
        if(!$jobs_info['is_edit']) {
            if ($jobs_info['old_zhao_type_id'] == 1) { //常规 6个月
                M('jobs')->where(['id' => $order_info['jobs_id']])->setField('zhao_end_time', date('Y-m-d', strtotime('+6 month')));
            } elseif ($jobs_info['old_zhao_type_id'] == 2) {//急招   3个月
                M('jobs')->where(['id' => $order_info['jobs_id']])->setField('zhao_end_time', date('Y-m-d', strtotime('+3 month')));
            } elseif ($jobs_info['old_zhao_type_id'] == 3) {//短期  3个月
                M('jobs')->where(['id' => $order_info['jobs_id']])->setField('zhao_end_time', date('Y-m-d', strtotime('+3 month')));
            } elseif ($jobs_info['old_zhao_type_id'] == 3) {//项目专场 6个月
                M('jobs')->where(['id' => $order_info['jobs_id']])->setField('zhao_end_time', date('Y-m-d', strtotime('+6 month')));
            }
            if($jobs_info['is_again']){
                M('jobs')->where(['id'=>$jobs_info['id']])->setField('is_again',0);
            }
        }else{
            if($jobs_info['is_shou']){
                if ($jobs_info['old_zhao_type_id'] == 1) { //常规 6个月
                    M('jobs')->where(['id' => $order_info['jobs_id']])->setField('zhao_end_time', date('Y-m-d', strtotime('+6 month')));
                } elseif ($jobs_info['old_zhao_type_id'] == 2) {//急招   3个月
                    M('jobs')->where(['id' => $order_info['jobs_id']])->setField('zhao_end_time', date('Y-m-d', strtotime('+3 month')));
                } elseif ($jobs_info['old_zhao_type_id'] == 3) {//短期  3个月
                    M('jobs')->where(['id' => $order_info['jobs_id']])->setField('zhao_end_time', date('Y-m-d', strtotime('+3 month')));
                } elseif ($jobs_info['old_zhao_type_id'] == 3) {//项目专场 6个月
                    M('jobs')->where(['id' => $order_info['jobs_id']])->setField('zhao_end_time', date('Y-m-d', strtotime('+6 month')));
                }
                M('jobs')->where(['id'=>$jobs_info['id']])->setField('is_shou',0);
            }
            M('jobs')->where(['id'=>$jobs_info['id']])->setField('is_edit',0);
        }
    }
    if($zhao_end_time || ($taocan_info && $zhao_end_time)){
        if(!$jobs_info['is_edit']){
            M('jobs')->where(['id'=>$order_info['jobs_id']])->setField('zhao_end_time',$zhao_end_time);
        }else{
            if($jobs_info['is_shou']){
                M('jobs')->where(['id'=>$order_info['jobs_id']])->setField('zhao_end_time',$zhao_end_time);
                M('jobs')->where(['id'=>$jobs_info['id']])->setField('is_shou',0);
            }
            M('jobs')->where(['id'=>$jobs_info['id']])->setField('is_edit',0);
        }
    }
    //   var_dump( M('jobs')->getLastSql());die;

}


/**
 * 获取微信Accesstoken
 */
function wxAccessToken(){
    $access_token = S('wxxcx_access_token');
    if ($access_token) return $access_token;

    $pay_type = D('Payment')->get_cache();

    $url = "https://api.weixin.qq.com/cgi-bin/token";
    $param  = [
        'grant_type'=> 'client_credential',
        'appid'     => $pay_type['wxpay']['parameter1'],
        'secret'    => $pay_type['wxpay']['parameter2']
    ];
    $result = PublicFunction::curl($url, $param, [], 'GET');
    //$jsoninfo = json_decode($result, true);print_r($result);exit;
    $access_token = $result["access_token"];
    //更新数据
    S('wxxcx_access_token', $access_token, 7200);
    return $access_token;
}

/**
 * 获取微信二维码
 * @param string $path 小程序路径
 */
function qrcode($path){

    if(empty($path)) return false;
    $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=".wxAccessToken();
    $param  = [
        'path'=> $path,
    ];
    $result = PublicFunction::curl($url, json_encode($param), [], 'post');

    return $result;
}

/**
 * 微信小程序消息发送
 * @param string $path 小程序路径
 */
function wxMessageSend($code, $id, $data){
    //$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".wxAccessToken();
    $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".wxAccessToken();

    $tmp    =[
        9187    => [
            'id'    => 'pGAOseW-LkhOqrVBHFc-xeyK9IsArWE-4yeQ6T8RGt4',
            'num'   => '9187',
            'title' => '顾问审核结果通知',
        ],
        17837   => [
            'id'    => '0iCs9JSwwLLZknlB5xNDyStAbKYlSt_6ZIxGWv-U9EY',
            'num'   => '17837',
            'title' => '企业认证通知',
        ]
    ];

    if(empty($tmp[$id])) return false;

    if(!is_array($data)) return false;
    /*$param  = [
        'touser'        => $code,//用户Openid
        'template_id'   => '0iCs9JSwwLLZknlB5xNDyStAbKYlSt_6ZIxGWv-U9EY',
        'page'          => 'pages/user/index',
        'form_id'       => '19568',
        'data'          => [
            'thing2' => ['value'=>'张全蛋有限公司'],
            'phrase1'=> ['value'=>'审核通过'],
            'time3'=> ['value'=>date('Y-m-d H:i:s', time())],
            'time4'=> ['value'=>date('Y-m-d H:i:s', time())],
        ],
        'miniprogram_state'=> 'trial',
    ];*/

    $param  = [
        'touser'        => $code,//用户Openid
        'template_id'   => $tmp[$id]['id'],
        'page'          => 'pages/user/index',
        'form_id'       => $id,
        'data'          => $data,
        'miniprogram_state'=> 'trial',
    ];
    $result = PublicFunction::curl($url, json_encode($param), [], 'post');

    return $result;
}
 /**
     * 根据出生年月日获取用户年龄
     * @param  [date]   $birthday   [年月日格式Y-m-d]
     * @return [int]    $age        [年龄]
     */
    function get_age($birthday){
        if($birthday == "0000-00-00"){
            return "";
            exit();
        }else{
            $birthday = strtotime($birthday);
            $year = date('Y', $birthday);
            if(($month = (date('m') - date('m', $birthday))) < 0){
                $year++;
            }else if ($month == 0 && date('d') - date('d', $birthday) < 0){
                $year++;
            }
            $age = date('Y') - $year;
            return $age;
        }
    }
    /**
 * 只保留字符串首尾字符，隐藏中间用*代替（两个字符时只显示第一个）
 * @param string $user_name 姓名
 * @return string 格式化后的姓名
 */
    function substr_cut($user_name){
        $strlen     = mb_strlen($user_name, 'utf-8');
       $firstStr     = mb_substr($user_name, 0, 1, 'utf-8');
       $lastStr     = mb_substr($user_name, -1, 1, 'utf-8');
     return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}


    function get_job_in_money($gw_uid,$jobs_info,$type=1,$server_money=0,$xishu_rate=0)
{
    $money_info=seal_month_price($jobs_info);
    //查询顾问的等级信息
    $guwen_info=M('members')->field('advisor_level')->where(['uid'=>$gw_uid])->find();
    //  var_dump($jobs_info);die;
    $level_info=M('guwen_level')->where(['level'=>$guwen_info['advisor_level']])->find();
//        var_dump($guwen_info);
//        var_dump($gw_uid);die;
    if($jobs_info['fa_type']==4){
      // var_dump($money_info);die;
        if($type==1){
            $money=number_format($money_info['ru_zhi']*$level_info['zhao_ti_rate']/100,2,'.','');
      //   var_dump($level_info['zhao_ti_rate']);die;
           // var_dump($xishu_rate);
            if($xishu_rate>0){
               // var_dump(2);
                $money=$money*$xishu_rate;
            }
            //die;
            $price=$money_info['ru_zhi'];
        }else{
            $money=number_format($money_info['ru_zhi_month']*$level_info['zhao_ti_rate']/100,2,'.','');
            if($xishu_rate>0){
                $money=$money*$xishu_rate;
            }
            $price=$money_info['ru_zhi_month'];
        }
    }else{
        if($type==1){
            $money=number_format($money_info['ru_zhi']*$level_info['zhao_ti_rate']/100,2,'.','');
            $price=$money_info['ru_zhi'];
        }else{
            $money=number_format($money_info['ru_zhi_month']*$level_info['zhao_ti_rate']/100,2,'.','');
            $price=$money_info['ru_zhi_month'];
        }
    }
    $data['give_money']=$money;
    $data['systerm_get_money']=$price-$money;
    $data['all_money']=$price;
    return $data;

}


/**
 * 判断两日期是不是同一周
 * 星期是按周日到周六
 */
function getSameWeek($pretime,$aftertime){
    $flag = false;//默认不是同一周
    $afweek = date('w',$aftertime);//当前是星期几
    $mintime = $aftertime - $afweek * 3600*24;//一周开始时间
    $maxtime = $aftertime + (7-$afweek)*3600*24;//一周结束时间
    if ( $pretime >= $mintime && $pretime <= $maxtime){//同一周
        $flag = true;
    }
    return $flag;
}


/**
 * 根据出生年月计算年轻
 */
function birthday($birthday){
    list($year,$month,$day) = explode("-",$birthday);
    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;

    if ( $month_diff < 0){
        $year_diff--;
    }else{
        if($month_diff==0 && $day_diff < 0){
            $year_diff--;
        }
    }
    return $year_diff;
}

  function add_bu_jiao_order_log($uid,$order_id,$oid,$money,$payment,$payment_cn,$jobs_id)
{
    //判断订单是否存在
    $row=M('com_bu_jiao_order')->where([
        'uid'=>$uid,
        'order_id'=>$order_id,
        'jobs_id'=>$jobs_id
    ])->find();
    if($row){
       //修改支付方式
        M('com_bu_jiao_order')->where(['order_id'=>$order_id,'uid'=>$uid])->save([
            'payment'=>$payment,
            'payment_cn'=>$payment_cn,
        ]);
        return $row['id'];
    }else{
        $res=  M('com_bu_jiao_order')->add([
            'order_id'=>$order_id,
            'uid'=>$uid,
            'pay_status'=>0,
            'pay_time'=>0,
            'oid'=>$oid,
            'add_time'=>NOW_TIME,
            'pay_money'=>$money,
            'payment'=>$payment,
            'payment_cn'=>$payment_cn,
            'jobs_id'=>$jobs_id
        ]);
        return $res;
    }


}







